package com.dgz.common.security.service;

import cn.hutool.core.lang.UUID;
import com.dgz.common.core.constants.CacheConstants;
import com.dgz.common.core.constants.JwtConstants;
import com.dgz.common.redis.service.RedisService;
import com.dgz.common.core.domain.LoginUser;
import com.dgz.common.core.uitls.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: DongGuoZhen
 * @Date: 2024/12/06/16:15
 * @Description:
 */
// 用户登录token方法
@Service
@Slf4j
public class TokenService {

    @Autowired
    private RedisService redisService;

    public String createToken(long userId, String secret,Integer identity,String nickName,String headImage) {
        String userKey = UUID.fastUUID().toString();
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtConstants.LOGIN_USER_ID, userId);
        claims.put(JwtConstants.LOGIN_USER_KEY, userKey);
        String token = JwtUtils.createToken(claims, secret);
        String tokenKey = getTokenKey(userKey);
        LoginUser loginUser = new LoginUser();
        loginUser.setIdentity(identity);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(tokenKey, loginUser, CacheConstants.EXP, TimeUnit.MINUTES);
        return token;
    }


    /**
     * 延长token有效期  就是延长redis缓存的有效期
     * @param token token
     * 在身份认证通过之后，请求到达controller之前延长token有效期，使其在redis中缓存的时间更长
     */
    public void extendToken(String token, String secret) {
        String userKey = getUserKey(token, secret);
        if (userKey == null) {
            return;
        }
        String tokenKey = getTokenKey(userKey);
        // 延长redis缓存的有效期 剩余180分钟 延长
        Long expire = redisService.getExpire(tokenKey, TimeUnit.MINUTES); // 单位分钟
        if(expire!= null && expire < CacheConstants.REFRESH_TIME) {
            redisService.expire(tokenKey,CacheConstants.EXP,TimeUnit.MINUTES); // 延长有效期 分钟
        }
    }

    public LoginUser getLoginUser(String token, String secret) {
        String userKey = getUserKey(token, secret);
        if(userKey == null) {
            return null;
        }
        return redisService.getCacheObject(getTokenKey(userKey), LoginUser.class);
    }

    public boolean deleteLoginUser(String token, String secret) {
        String userKey = getUserKey(token, secret);
        if(userKey == null) {
            return false;
        }
        return redisService.deleteObject(getTokenKey(userKey));
    }

    public Long getUserId(String token,String secret){
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息 解析payload中信息
            if (claims == null) {
                log.error("解析token失败token={}, 出现异常",token);
                return null;
            }
        } catch (Exception e) {
            log.error("解析token失败token={}, 出现异常",token, e);
            return null;
        }
        return Long.valueOf(JwtUtils.getUserId(claims)); //获取jwt中的key
    }

    public String getUserKey(String token,String secret) {
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息 解析payload中信息
            if (claims == null) {
                log.error("解析token失败token={}, 出现异常",token);
                return null;
            }
        } catch (Exception e) {
            log.error("解析token失败token={}, 出现异常",token, e);
            return null;
        }
        return JwtUtils.getUserKey(claims); //获取jwt中的key

    }

    public void refreshLoginUser(String nickName, String headImage, String userKey) {
        String tokenKey = getTokenKey(userKey);
        LoginUser loginUser = redisService.getCacheObject(tokenKey, LoginUser.class);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(tokenKey, loginUser);
    }


    private String getTokenKey(String userKey) {
        return CacheConstants.LOGIN_TOKEN_KEY + ":" +  userKey;
    }
}
